<template>
	<view class="order-pages" :style="{background:pageColor}">
		<!-- #ifndef H5 -->
		<uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" :title="navTitle" color="#ffffff"
			:backgroundColor="primaryColor">
		</uni-nav-bar>
		<view :style="{height:`${configInfo.navBarHeight}px`}"></view>
		<fixed :top="configInfo.navBarHeight">
		<!-- #endif -->
			<!-- #ifdef H5 -->
			<fixed>
			<!-- #endif -->
              <view style="display: flex;align-items: center;justify-content: center;width: 100%;background-color: #fff;">

				<tab :isSearch="true" @change="handerTabChange" :list="tabList" :activeIndex="activeIndex*1" :activeColor="primaryColor"
					:color="configInfo.order_list_type===2?'#7A7D7C':'#333'" :width="100/tabList.length + '%'"
					height="94rpx" lineRadius="20rpx" lineWidth="32rpx" lineHeight="8rpx" lineBottom="16rpx"></tab>
				<view class="b-1px-b"></view>
				</view>
			</fixed>

			<view @tap.stop="goDetail(index,'detail')" class="item-child mt-md ml-md mr-md fill-base rel" :class="[
				         { 'pd-lg radius-16': configInfo.order_list_type === 1 },
				         { 'type-2 radius-24': configInfo.order_list_type === 2 }
				       ]" v-for="(item,index) in list.data" :key="index">
				<view v-if="item.is_add">
					<view class="bell-tag flex-center f-icontext c-base abs" :style="{background:primaryColor}">加钟服务
					</view>
					<view class="space-md"></view>
				</view>
				<view class="flex-between pb-lg b-1px-b">
					<view class="f-paragraph c-title max-450 ellipsis" @tap.stop="toCopy(item.order_code)"
						v-if="configInfo.order_list_type === 1">
						订单号：{{item.order_code}}
					</view>
					<view class="flex-y-center f-paragraph" style="color:#222724" @tap.stop="toCopy(item.order_code)"
						v-if="configInfo.order_list_type === 2">
						<view style="color: #4e5250">订单号：</view>
						<view class="max-400 ellipsis">{{ item.order_code }}</view>
					</view>
					<!-- // pay_type 1待支付，2待服务，3技-师接单，4技-师出发，5技-师到达，6服务中，7已完成 -->
					<view class="" :class="[
					            { 'f-paragraph': configInfo.order_list_type === 2 }
					          ]" :style="{color:item.pay_type==1?'#FF2444': [2,3,4,5,6].includes(item.pay_type)?subColor: item.pay_type == 7 ? '#11C95E' : '#333'}"
                style="font-size: 28rpx;"
          >
						{{statusType[item.pay_type]}}
					</view>
				</view>
				<view class="flex-center mt-lg" v-for="(aitem,aindex) in item.order_goods" :key="aindex">
					<!-- #ifdef H5 -->
					<view class="cover radius-16">
						<view class="h5-image cover radius-16"
							:style="{ backgroundImage : `url('${aitem.goods_cover}')`}">
						</view>
					</view>
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<image mode="aspectFill" class="cover radius-16" :src="aitem.goods_cover"></image>
					<!-- #endif -->
					<view class="flex-1 ml-md" v-if="configInfo.order_list_type===1">
						<view class="flex-between" style="height: 42rpx">
							<view class="f-mini-title c-title text-bold max-400 ellipsis">
								{{aitem.goods_name}}
							</view>
							<!--<view class="f-desc c-desc flex-y-baseline">x<text class="font-num">{{aitem.num}}</text>
							</view> -->
							<view class="" style="color: #3D3D3D;font-size:32rpx">
								￥{{aitem.goods_price || "199.00"}}
							</view>
						</view>
						<view class="flex-center" style="height: 34rpx;"
							:style="{marginTop:aindex==item.order_goods.length-1?'6rpx':'40rpx'}">
							<view class="flex-1 flex-y-center f-caption c-caption">
								{{$t('action.attendantName').substring(0, 2) === '服务' ? '' : '服务'}}{{$t('action.attendantName')}}
								<view class="ml-md max-280 ellipsis">
									{{item.coach_info ? item.coach_info.coach_name : '-'}}
								</view>
							</view>
							<view class="f-caption c-warning flex-y-baseline" v-if="aitem.refund_num>0">已退x<text
									class="font-num">{{aitem.refund_num}}</text>
							</view>
						</view>
						<view class="flex-y-center f-caption c-caption" style="height: 34rpx;">预约时间<view class="ml-md">
								{{item.start_time}}
							</view>
						</view>
						<!--<view class="flex-y-center f-caption c-caption" v-if="aindex==item.order_goods.length-1">总计：
							<view class="flex-y-baseline c-warning text-bold font-num">¥
								<view class="f-title">{{item.pay_price}}</view>
							</view>
						</view> -->
					</view>
					<view class="f-desc c-desc flex-y-baseline" style="color: #8A8A8A;font-size:16rpx" v-if="aitem.refund_num<=0">x<text class="font-num">{{aitem.num}}</text></view>
					<view class="flex-1 ml-md" v-if="configInfo.order_list_type === 2">
						<view class="flex-between" style="height: 40rpx;">
							<view class="c-title text-bold ellipsis" style="max-width: 200px">
								{{ aitem.goods_name }}
							</view>
							<view class="f-icontext c-desc flex-y-baseline">x<text
									class="font-num">{{ aitem.num }}</text></view>
						</view>
						<view class="flex-center mt-sm" style="height: 34rpx;">
							<view class="flex-1 flex-y-center f-caption" style="color: #7a7d7c">
								{{$t('action.attendantName').substring(0, 2) === '服务' ? '' : '服务'}}{{ $t('action.attendantName') }}：
								<view style="color: #222724">{{item.coach_info ? item.coach_info.coach_name : '-'}}
								</view>
							</view>

							<view class="f-caption c-warning ml-sm flex-y-baseline" v-if="aitem.refund_num > 0">
								已退x<text class="font-num">{{ aitem.refund_num }}</text>
							</view>
						</view>
						<view class="flex-y-center f-caption mt-sm" style="height: 34rpx;color: #7a7d7c">
							开始时间：
							<view style="color: #222724">{{ item.start_time }}</view>
						</view>
					</view>
				</view>
				<view class="flex-top" style="display: flex;justify-content: space-between;font-size:24rpx" v-if="configInfo.order_list_type === 1">
					<view class="left-num" style="color: #8A8A8A;">
						共{{item.order_goods.length}}件
					</view>
					<view class="right-jine" style="color: #3D3D3D;">
						待付款￥{{ item.pay_price }}
					</view>
				</view>
				<view class="flex-between pt-lg" :class="[{ 'mt-lg b-1px-t': configInfo.order_list_type === 2 }]">
					<view>
						<view class="flex-y-center f-caption" style="color: #7a7d7c"
							v-if="configInfo.order_list_type === 2">
							合计:
							<view class="flex-y-baseline font-num" style="color: #f84e2c; margin-left: 3px">
								¥
								<view class="f-title text-bold">{{ item.pay_price }}</view>
							</view>
						</view>
					</view>
					<view class="flex-warp">
						<!-- 待支付 -->
						<block v-if="item.pay_type == 1">
							<button @tap.stop="toChangeItem(index,'cancel_item')" class="clear-btn order" style="padding:14rpx 48rpx;border-radius: 34rpx;background-color: #FAF9F9;font-weight: 400;color: #666666;border:none">取消订单</button>
							<button @tap.stop="toPay(index)" class="clear-btn order"
								:style="{color:'#fff', background: primaryColor}" style="padding:14rpx 48rpx;border-radius: 34rpx;font-weight: 400;color: #FFFFFF;border:none">去付款</button>
						</block>
						<!-- 支付超时 -->
						<block v-if="item.pay_type == -1 || item.pay_type == 7">
							<button @tap.stop="toChangeItem(index,'del_item')" class="clear-btn order" style="border-radius: 34rpx;background-color: #FAF9F9;font-weight: 400;color: #666666;border:none">删除</button>
						</block>
						<!-- 待服务 -->
						<button @tap.stop="goDetail(index,'refund')" class="clear-btn order"
							v-if="item.can_refund > 0" style="border-radius: 34rpx;background-color: #FAF9F9;font-weight: 400;color: #666666;border:none">退款</button>
						<!-- 服务中 -->
						<!-- is_add 加钟订单 -->
						<button
							@tap.stop="$util.goUrl({url:`/user/pages/bell/list?id=${item.id}&coach_id=${item.coach_id}&tab=${item.is_add?1:0}`})"
							class="clear-btn order"
							:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}"
							v-if="item.pay_type == 6 && (item.is_add || (!item.is_add && item.can_add_order))">{{item.is_add?'升级项目':'加钟/升级'}}</button>
						<button @tap.stop="toEndOrder(index)" class="clear-btn order"
							:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}"
							v-if="item.pay_type == 6">完成服务</button>
						<!-- 已完成 -->
						<block v-if="item.coach_id && item.pay_type == 7 && !item.is_add">
							<button @tap.stop="goDetail(index,'evaluate')" class="clear-btn order"
								v-if="!item.is_comment" style="border-radius: 34rpx;background-color: #FAF9F9;font-weight: 400;color: #666666;border:none">去评价</button>
							<button @tap.stop="toAgain(index)" class="clear-btn order"
								:style="{color:'#fff',background:primaryColor,borderColor:primaryColor}"
								v-if="item.can_again" style="border-radius: 34rpx;font-weight: 400;color: #FFFFFF;border:none">再来一单</button>
						</block>
					</view>
				</view>
				
			</view>

			<load-more :noMore="list.current_page>=list.last_page&&list.data.length>0" :loading="loading">
			</load-more>
			<abnor :tip="[{text: '暂无订单数据'}]" v-if="!loading&&list.data.length<=0&&list.current_page==1"
				:isCenter="true"></abnor>

			<view class="space-lg"></view>

			<common-popup @confirm="confirmOperItem" ref="cancel_item" type="CANCEL_ORDER" :info="popupInfo">
			</common-popup>
			<common-popup @confirm="confirmOperItem" ref="del_item" type="DELETE_ORDER"
				:info="popupInfo"></common-popup>
			<common-popup @confirm="confirmOperItem" ref="end_item" type="END_ORDER" :info="popupInfo"></common-popup>

			<!-- 完成服务 -->
			<uni-popup ref="end_order_item" type="bottom" :custom="true">
				<view @touchmove.stop.prevent class="common-popup-content fill-base"
					style="width: 100%;border-radius: 34rpx 34rpx 0 0;"
					v-if="endOrderInfo && endOrderInfo.end_order_rules">
					<view class="title">温馨提示</view>
					<scroll-view scroll-y class="f-mini-title c-title mt-md" style="width: 100%;max-height:50vh">
						<text decode="emsp" style="word-break:break-all;">{{endOrderInfo.end_order_rules}}</text>
					</scroll-view>
					<view @tap.stop="isAgree=!isAgree" class="mt-md pt-lg b-1px-t" style="width:100%">
						<view class="flex-y-center" style="height:36rpx">
							<i class="iconfont mr-sm" :class="isAgree?'icon-xuanze-fill':'icon-xuanze'"
								style="font-size: 36rpx" :style="{color:isAgree?primaryColor:'#999'}"></i>本人已认真阅读并同意上述内容
						</view>
					</view>
					<view class="button">
						<view @tap.stop="$refs.end_order_item.close()" class="item-child">
							取消
						</view>
						<view @tap.stop="toConfirmEndOrder" class="item-child"
							:style="{background: primaryColor,color:'#fff'}">
							{{endOrderInfo.user_end_sign?'确认签字':'确认完成'}}
						</view>
					</view>
					<view class="space-safe"></view>
					</block>
				</view>
			</uni-popup>

			<view :style="{height: `${configInfo.tabbarHeight}px`}"></view>
			<longbingbing-tabbar :cur="4"></longbingbing-tabbar>
			<longbingbing-change-user-type></longbingbing-change-user-type>
			<longbingbing-customer-item></longbingbing-customer-item>

			<!-- #ifdef MP-WEIXIN -->
			<user-privacy ref="user_privacy" :show="false"></user-privacy>
			<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from "vuex"
	export default {
		components: {},
		data() {
			return {
				options: {},
				navTitle: '',
				statusType: {
					'-1': '已取消',
					1: '待付款',
					2: '待接单',
					3: '待服务',
					4: this.$t('action.attendantName') + '出发',
					5: this.$t('action.attendantName') + '到达',
					6: '服务中',
					7: '已完成',
					8: '待转单'
				},
				loading: true,
				popupInfo: {},
				endOrderInfo: {},
				isAgree: false,
				lockTap: false,
				payInd: '',
			}
		},
		computed: mapState({
			activeIndex: state => state.order.activeIndex,
			tabList: state => state.order.tabList,
			param: state => state.order.param,
			list: state => state.order.list,
			configInfo: state => state.config.configInfo,
			haveOperItem: state => state.order.haveOperItem,
		}),
		async onLoad(options) {
			let {
				tab = 0
			} = options
			this.updateOrderItem({
				key: 'activeIndex',
				val: tab
			})
			// 支付后需刷新页面
			await this.$util.toAsyAccLogin()
			await this.initIndex()
		},
		onShow() {
			// #ifdef APP-PLUS
			var args = plus.runtime.arguments
			if (args == 'wechat-adapay-suc') {
				let {
					payInd = 0
				} = this
				if (this.activeIndex == 0) {
					this.list.data[payInd].pay_type = 2
				} else {
					this.list.data.splice(payInd, 1)
				}
			}
			plus.runtime.arguments = null
			plus.runtime.arguments = ""
			// #endif
			if (!this.haveOperItem) return
			this.initRefresh()
		},
		onPullDownRefresh() {
			// #ifndef APP-PLUS
			uni.showNavigationBarLoading()
			// #endif
			this.initRefresh()
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			if (this.list.current_page >= this.list.last_page || this.loading) return;
			this.loading = true;
			this.getList(this.param.page + 1);
		},
		methods: {
			...mapActions(['getConfigInfo', 'getOrderList']),
			...mapMutations(['updateOrderItem']),
			async initIndex(refresh = false) {
				if (!this.configInfo.id || refresh || !this.userInfo.id) {
					await this.getConfigInfo()
				}
				this.updateOrderItem({
					key: 'haveOperItem',
					val: false
				})
				await this.getList(1)
				this.initNavTitle()

				let {
					status: coach_status = 0,
					coach_position = 0
				} = this.userCoachStatus

				if (coach_position && coach_status == 2) {
					this.$util.getCoachUtilLoca()
				}
				// #ifdef H5
				if (!refresh) {
					this.$jweixin.hideOptionMenu()
				}
				// #endif

			},
			async initRefresh() {
				await this.initIndex(true)
			},
			async initNavTitle() {
				let {
					tabBar
				} = this.configInfo
				if (tabBar && tabBar.length > 0) {
					let ind = tabBar.findIndex(item => {
						return item.id == 4
					})
					let navTitle = ind == -1 ? '订单' : tabBar[ind].name
					this.navTitle = navTitle
					// #ifdef H5
					uni.setNavigationBarTitle({
						title: navTitle
					})
					// #endif
				}
			},
			async getList(page = 0) {
				if (page) {
					let param = this.$util.deepCopy(this.param)
					param.page = page
					this.updateOrderItem({
						key: 'param',
						val: param
					})
				}
				let {
					list: oldList,
					param,
					tabList,
					activeIndex
				} = this
				param.pay_type = tabList[activeIndex].id
				try {
					await this.getOrderList(param)
					this.loading = false
					this.$util.hideAll()
				} catch (e) {
					this.loading = false
					this.$util.hideAll()
				}
			},
			handerTabChange(index) {
				this.updateOrderItem({
					key: 'activeIndex',
					val: index
				})
				uni.pageScrollTo({
					scrollTop: 0
				})
				this.getList(1)
			},
			async toEndOrder(index) {
				let {
					id
				} = this.list.data[index]
				this.popupInfo = {
					id,
					index,
					refs_key: 'end_item'
				}
				let [{
					end_order_rules,
					user_end_sign
				}] = await Promise.all([this.$api.base.payOrderInfoConfig(), this.$api.order.canEndOrder({
					id
				})])
				this.endOrderInfo = {
					id,
					end_order_rules,
					user_end_sign
				}
				this.isAgree = false
				this.$refs.end_order_item.open()
			},
			async toConfirmEndOrder() {
				let {
					id,
					user_end_sign
				} = this.endOrderInfo
				if (!this.isAgree) {
					this.$util.showToast({
						title: `请先阅读并同意上述内容`
					})
					return
				}
				if (!user_end_sign) {
					await this.confirmOperItem()
					this.$refs.end_order_item.close()
					return
				}
				this.$refs.end_order_item.close()
				this.$util.goUrl({
					url: `/user/pages/order/sign?id=${id}&endorder=1`
				})
			},
			// 取消订单/删除订单/完成服务
			async toChangeItem(index, refs_key) {
				if (this.lockTap) return
				let {
					id,
					order_code,
					order_goods,
					pay_type,
				} = this.list.data[index]
				let {
					goods_cover: image,
				} = order_goods[0]
				this.popupInfo = {
					id,
					name: `单号：${order_code}`,
					image,
					index,
					refs_key
				}
				this.$refs[refs_key].open()
			},
			// 确认：取消订单/删除订单/完成服务
			async confirmOperItem() {
				let {
					id,
					index,
					refs_key,
				} = this.popupInfo
				let methodArr = {
					'cancel_item': ['cancelOrder', '取消成功', -1],
					'del_item': ['delOrder', '删除成功', -1],
					'end_item': ['endOrder', '完成成功', 7]
				}
				let methodModel = methodArr[refs_key][0]
				let title = methodArr[refs_key][1]
				let pay_type = methodArr[refs_key][2]
				if (this.lockTap) return
				this.lockTap = true
				try {
					this.$refs[refs_key].close()
					await this.$api.order[methodModel]({
						id
					})
					if (this.activeIndex == 0 && refs_key !== 'del_item') {
						this.list.data[index].pay_type = pay_type
					} else {
						this.list.data.splice(index, 1)
					}
					if (refs_key == 'end_item') {
						this.list.data[index].can_refund = 0
					}
					this.$util.showToast({
						title
					})
					setTimeout(() => {
						this.lockTap = false
					}, 1000)
				} catch (e) {
					setTimeout(() => {
						this.getList(1)
						this.lockTap = false
					}, 2000)
				}
			},
			// 去支付
			async toPay(index) {
				this.payInd = index
				if (this.lockTap) return
				this.lockTap = true
				this.$util.showLoading()
				let {
					id,
					pay_model,
					order_code
				} = this.list.data[index]

				try {
					let {
						pay_list
					} = await this.$api.order.rePayOrder({
						id
					})
					this.$util.hideAll()
					if (pay_list) {
						if (pay_model == 3) {
							pay_list = {
								orderInfo: pay_list,
								provider: 'alipay'
							}
						}

						// #ifdef H5
						if (pay_model == 3) {
							let {
								autograph
							} = this
							let alipay_params = `?autograph=${autograph}&id=${id}`
							pay_list = Object.assign({}, pay_list, {
								order_id: id,
								page_url: `/pages/order?tab=2`,
								alipay_params
							})
							this.updateOrderItem({
								key: 'alipayOrderParams',
								val: pay_list
							})
							this.$util.goUrl({
								url: `/user/pages/alipay-result${alipay_params}`
							})
							this.lockTap = false
							setTimeout(() => {
								this.initRefresh()
							}, 3000)
							return
						}
						// #endif

						// #ifdef APP-PLUS
						if (pay_model === 1 && pay_list.adapay) {
							pay_list = Object.assign(pay_list, {
								type: 0,
								order_code
							})
						}
						// #endif

						try {
							let payResType = await this.$util.pay(pay_list)
							if (payResType === 'adapay_app_wechat') {
								this.lockTap = false
								return
							}
							if (payResType === 'adapay_app_alipay') {
								setTimeout(() => {
									this.toPayResult(index)
								}, 1000)
								return
							}
							this.$util.showToast({
								title: `支付成功`
							})
							this.lockTap = false
							if (this.activeIndex == 0) {
								this.list.data[index].pay_type = 2
							} else {
								this.list.data.splice(index, 1)
							}
						} catch (e) {
							this.$util.showToast({
								title: `支付失败`
							})
							this.lockTap = false
							return
						}
					}
				} catch (e) {
					setTimeout(() => {
						this.lockTap = false
						this.$util.hideAll()
					}, 2000)
				}
			},
			async toPayResult(index) {
				this.lockTap = false
				let {
					pay_model
				} = await this.$api.order.orderInfo({
					id
				})
				if (pay_model != 2) return
				this.$util.showToast({
					title: `支付成功`
				})
				if (this.activeIndex == 0) {
					this.list.data[index].pay_type = 2
				} else {
					this.list.data.splice(index, 1)
				}
			},
			// 去核销
			async toHx(index) {
				let {
					id,
					qr: image
				} = this.list.data[index]
				this.popupInfo = {
					id,
					image
				}
				this.$refs.hx_item.open()
			},
			// 订单详情/申请退款/去评价
			async goDetail(index, page) {
				let {
					id
				} = this.list.data[index]
				let flag = true
				if (page == 'refund') {
					flag = await this.$api.order.canRefundOrder({
						id
					})
				}
				if (!flag) {
					this.list.data[index].can_refund = 0
					this.$util.showToast({
						title: `当前订单不支持退款哦`
					})
					return
				}
				let url = `/user/pages/order/${page}?id=${id}`
				this.$util.goUrl({
					url
				})
			},
			// 再来一单
			async toAgain(index) {
				let {
					id: order_id,
					coach_id
				} = this.list.data[index]
				await this.$api.order.onceMoreOrder({
					order_id
				})
				this.$util.goUrl({
					url: `/user/pages/order?id=${coach_id}`
				})
			},
			toCopy(url) {
				// #ifdef MP-WEIXIN
				let privacyCheck = this.$refs.user_privacy.check()
				if (privacyCheck) {
					this.$refs.user_privacy.open()
					return
				}
				// #endif
				this.$util.goUrl({
					url,
					openType: 'copy'
				})
			}
		}
	}
</script>


<style lang="scss">
	.order-pages {
		.item-child.type-2 {
			padding: 24rpx;
			box-shadow: 0 4rpx 24rpx 0 rgba(0, 0, 0, 0.06),
				0 1 12rpx 0 rgba(0, 0, 0, 0.04);

			.b-1px-b::after {
				color: rgba(34, 39, 36, 0.08)
			}

			.b-1px-t::before {
				color: rgba(34, 39, 36, 0.08)
			}

			.cover {
				width: 180rpx;
				height: 136rpx;
				object-fit: cover;
				border-radius: 24rpx;
			}

			.pt-lg {
				padding-top: 24rpx;
			}

			.pb-lg {
				padding-bottom: 24rpx;
			}

			.mt-lg {
				margin-top: 24rpx;
			}

			.order {
				min-width: 130rpx;
				height: 56rpx;
				font-size: 24rpx;
				border: 1rpx solid #c7c7c7;
			}

			.order:nth-child(1) {
				margin-left: 0
			}
		}
	}
</style>